package com.atguigu.szdz.dcsyl.controller;

import com.alibaba.excel.EasyExcel;
import com.atguigu.szdz.dcsyl.common.utils.R;
import com.atguigu.szdz.dcsyl.common.listener.YxListener;
import com.atguigu.szdz.dcsyl.entity.YxDataEntity;
import com.atguigu.szdz.dcsyl.service.impl.YlDataServiceImpl;
import com.atguigu.szdz.dcsyl.utils.MapperUtils;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/yxData")
public class YxDataController {

    @Autowired
    private YlDataServiceImpl ylDataService;
    @Autowired
    private MapperUtils mapperUtils;

    /**
     * 导入excel文件
     */
    @Operation(summary = "导入excel文件并解析数据")
    @PostMapping("/importFile")
    public R importFile(@RequestParam("file") MultipartFile file, @RequestParam("well_id") Integer wellId) {
        //先去数据库查询是否有该井
        String sql = "select * from dc_well_info where id=" + wellId;
        List<Map<String, Object>> wellList = mapperUtils.queryBySql(sql);
        //获取井名
        String wellName = wellList.get(0).get("well_name").toString();
        List<YxDataEntity> list = new ArrayList<>();
        if (wellList.size() == 0) {
            return R.error("井不存在");
        }
        if (file.isEmpty()) {
            return R.error("文件不能为空");
        }

        String fileName = file.getOriginalFilename();
        if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
            return R.error("文件格式错误");
        }
        try (InputStream inputStream = file.getInputStream()) {
            YxListener yxListener = new YxListener();
            //解析excel文件
            EasyExcel.read(inputStream, YxDataEntity.class, yxListener).headRowNumber(2).sheet().doRead();
            //获取读到的数据
            list = yxListener.getList();
            //判断读出来的井名和选择的井名是否相同
            if (!list.get(0).getWellName().equals(wellName)) {
                return R.error("井名不一致,请重新上传");
            } else {
                //返回解析数据
                return R.ok().put("yxListData", list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("文件导入失败");
        }
    }

    /**
     * 导入岩性数据
     *
     * @param map
     * @return
     */
    @Operation(summary = "导入岩性数据")
    @PostMapping("/importYxData")
    public R importYxData(@RequestBody Map<String, Object> map) {
        //获取井ID
        Integer wellId = Integer.parseInt(map.get("wellId").toString());
        //获取数据vo->po
        List<YxDataEntity> list = new ArrayList<>();
        //获取数据
        List<Map<String, Object>> yxDataList = (List<Map<String, Object>>) map.get("yxDataList");
        for (Map<String, Object> yxDataMap : yxDataList) {
            YxDataEntity yxDataEntity = new YxDataEntity();
            yxDataEntity.setWellName(yxDataMap.get("wellName") != null ? yxDataMap.get("wellName").toString() : null);
            yxDataEntity.setDepth(yxDataMap.get("depth") != null ? Double.parseDouble(yxDataMap.get("depth").toString()) : null);
            yxDataEntity.setTopDepth(yxDataMap.get("topDepth") != null ? Double.parseDouble(yxDataMap.get("topDepth").toString()) : null);
            yxDataEntity.setBottomDepth(yxDataMap.get("bottomDepth") != null ? Double.parseDouble(yxDataMap.get("bottomDepth").toString()) : null);
            yxDataEntity.setSno(yxDataMap.get("sno") != null ? Integer.parseInt(yxDataMap.get("sno").toString()) : null);
            yxDataEntity.setSampleType(yxDataMap.get("sampleType") != null ? yxDataMap.get("sampleType").toString() : null);
            yxDataEntity.setStrata(yxDataMap.get("strata") != null ? yxDataMap.get("strata").toString() : null);
            yxDataEntity.setLithId(yxDataMap.get("lithId") != null ? yxDataMap.get("lithId").toString() : null);
            yxDataEntity.setS0(yxDataMap.get("s0") != null ? Double.parseDouble(yxDataMap.get("s0").toString()) : null);
            yxDataEntity.setS1(yxDataMap.get("s1") != null ? Double.parseDouble(yxDataMap.get("s1").toString()) : null);
            yxDataEntity.setS2(yxDataMap.get("s2") != null ? Double.parseDouble(yxDataMap.get("s2").toString()) : null);
            yxDataEntity.setS4(yxDataMap.get("s4") != null ? Double.parseDouble(yxDataMap.get("s4").toString()) : null);
            yxDataEntity.setPg(yxDataMap.get("pg") != null ? Double.parseDouble(yxDataMap.get("pg").toString()) : null);
            yxDataEntity.setGpi(yxDataMap.get("gpi") != null ? Double.parseDouble(yxDataMap.get("gpi").toString()) : null);
            yxDataEntity.setOpi(yxDataMap.get("opi") != null ? Double.parseDouble(yxDataMap.get("opi").toString()) : null);
            yxDataEntity.setTpi(yxDataMap.get("tpi") != null ? Double.parseDouble(yxDataMap.get("tpi").toString()) : null);
            yxDataEntity.setToc(yxDataMap.get("toc") != null ? Double.parseDouble(yxDataMap.get("toc").toString()) : null);
            yxDataEntity.setD(yxDataMap.get("d") != null ? Double.parseDouble(yxDataMap.get("d").toString()) : null);
            yxDataEntity.setHi(yxDataMap.get("hi") != null ? Double.parseDouble(yxDataMap.get("hi").toString()) : null);
            yxDataEntity.setTheDate(yxDataMap.get("theDate") != null ? LocalDate.parse(yxDataMap.get("theDate").toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd")) : null);
            yxDataEntity.setAnalyseUser(yxDataMap.get("analyseUser") != null ? yxDataMap.get("analyseUser").toString() : null);
            yxDataEntity.setAdditUser(yxDataMap.get("additUser") != null ? yxDataMap.get("additUser").toString() : null);
            yxDataEntity.setRemark(yxDataMap.get("remark") != null ? yxDataMap.get("remark").toString() : null);
            yxDataEntity.setTMax(yxDataMap.get("tMax") != null ? Double.parseDouble(yxDataMap.get("tMax").toString()) : null);
            list.add(yxDataEntity);
        }
        System.out.println(list);
        //先删除该井的所有数据
        ylDataService.removeYxData(wellId);
        //批量插入数据库
        ylDataService.saveBatchYx(list, wellId);
        return R.ok();
    }

    /**
     * 根据井id查询所有岩性数据
     */
    @PostMapping("/getYxData")
    public R getYxData(@RequestBody Map<String, Integer> map) {
        //获取井ID
        Integer wellId = map.get("wellId");
        //获取分页参数
        Integer currentPage = map.get("currentPage");
        //获取每页显示条数
        Integer pageSize = map.get("pageSize");
        //获取总条数
        String sql = "select count(*) from dc_yxdata where well_id=" + wellId;
        List<Map<String, Object>> contList = mapperUtils.queryBySql(sql);
        Integer total = Integer.parseInt(contList.get(0).get("count").toString());
        //总页数
        Integer totalPage = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        return R.ok().put("data", ylDataService.getYxData(wellId, currentPage, pageSize)).put("total", total).put("totalPage", totalPage);
    }
}
